package com.example.text.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.text.entity.AdminUserRole;
import com.example.text.entity.User;
import com.example.text.common.result.*;
import com.example.text.service.AdminRoleMenuService;
import com.example.text.service.AdminUserRoleService;
import com.example.text.service.UserService;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.util.Date;


@RestController
public class LoginController {

    //将Service注入Web层
    @Autowired
    UserService userService;

    @Autowired
    AdminUserRoleService adminUserRoleService;

    @CrossOrigin
    @ResponseBody
    @PostMapping(value = "api/login")
    public Result login(@RequestBody User requestUser) {
        String username = requestUser.getUsername();
        Subject subject = SecurityUtils.getSubject();
        //subject.getSession().setTimeout(10000);
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username, requestUser.getPassword());
        usernamePasswordToken.setRememberMe(true);
        try {
            subject.login(usernamePasswordToken);
            User user = userService.getByUserName(username);
            if (!user.isEnabled()) {
                return ResultFactory.buildFailResult("该用户已被禁用");
            }
            if(user.getStatus()==1){
                return  ResultFactory.buildFailResult("该用户已经登录过");
            }
            //修改登录状态
            userService.updateUserStatus(user,1);
            return  ResultFactory.buildSuccessResult(username);
        }catch (AuthenticationException e){

            String message="账号密码错误";

            return ResultFactory.buildFailResult(message);
        }
    }
    @CrossOrigin
    @PostMapping("api/register")
    @ResponseBody
    public Result register(@RequestBody User userEntity) {
        String username = userEntity.getUsername();
        String password = userEntity.getPassword();
        String email= userEntity.getEmail();
        String mobile=userEntity.getMobile();

        username = HtmlUtils.htmlEscape(username);
        userEntity.setUsername((username));
        User user= userService.getOne(new QueryWrapper<User>().eq("username", username));
       if(user !=null){
           String message = "用户名已被使用";
           return ResultFactory.buildFailResult(message);
       }
        // 生成盐,默认长度 16 位
        String salt = new SecureRandomNumberGenerator().nextBytes().toString();
        // 设置 hash 算法迭代次数
        int times = 2;
        // 得到 hash 后的密码
        String encodedPassword = new SimpleHash("md5", password, salt, times).toString();
        // 存储用户信息，包括 salt 与 hash 后的密码

        userEntity.setSalt(salt);
        userEntity.setPassword(encodedPassword);
         userEntity.setCreate_time(new Date());
         //当自己注册，默认注册id=0
        userEntity.setCreate_user_id(0);

        //创建用户的禁用设置为false
        userEntity.setEnabled(true);

        userEntity.setStatus(0);

        //默认头像
        userEntity.setCover("http://localhost:8080/api/file/5tbx3z.jpg");

        userService.save(userEntity);

        //初始为都为访客
        adminUserRoleService.addRoleByName(userEntity.getUsername());

        return ResultFactory.buildSuccessResult(userEntity);

    }
    @CrossOrigin
    @ResponseBody
    @GetMapping("api/logout/{name}")
    public Result logout(@PathVariable("name")String username){
        //修改登录状态
        System.out.println("登出的用户；"+username);
        User user= userService.getOne(new QueryWrapper<User>().eq("username", username));
        System.out.println("登出的用户；"+user);
        userService.updateUserStatus(user,0);

        Subject subject=SecurityUtils.getSubject();
        subject.logout();
        String message ="成功登出";
        return ResultFactory.buildSuccessResult(message);
    }
    @CrossOrigin
    @ResponseBody
    @GetMapping(value = "api/authentication")
    public String authentication(){
        System.out.println("验证成功");
        return "身份认证成功";
    }


}
